<template>
  <BasicDrawer
    :destroyOnClose="true"
    v-bind="$attrs"
    @register="registerDrawer"
    :showFooter="true"
    title="退款"
    width="680px"
    @ok="onSave"
    okText="保存"
    :maskClosable="false">

    <div style="font-weight: 500;font-size: 16px;color: #333333;padding: 8px 0;margin-bottom: 4px;">
      购买信息
    </div>

    <div
      style="background: #FFFFFF;box-shadow: 0 1px 6px 0 rgba(229,197,197,0.5);border-radius: 4px;padding: 12px;">
      <a-flex align="center" justify="space-between"
              style="background: #F9F9F9;box-shadow: inset 0 -1px 0 0 #FFF0F0;border-radius: 4px 4px 0 0;height: 56px;margin: -12px -12px 12px -12px;padding: 0 12px;">
        <span style="font-weight: 600;font-size: 18px;color: #C95E78;">{{ record.goodsName }}</span>
        <span style="font-weight: 600;font-size: 18px;color: #C95E78;">x{{ record.goodsQty }}</span>
      </a-flex>

      <a-flex>
        <div style="flex: 1">
          <div style="font-size: 14px;color: #6D414C;">卡项</div>
          <div style="font-size: 14px;color: #6D414C;margin-top: 8px;">{{
              record.cardConsumeName
            }}
          </div>
        </div>

        <div style="flex: 1">
          <div style="font-size: 14px;color: #6D414C;">美容师</div>
          <div style="font-size: 14px;color: #6D414C;margin-top: 8px;">{{
              record.cashierName
            }}
          </div>
        </div>

        <div style="flex: 1;text-align: right;">
          <div
            style="font-weight: 400;font-size: 14px;color: #999999;text-decoration:line-through;">
            <span>零售价</span><span>{{ record.totalShoppingPrice }}</span>
          </div>


          <div style="margin-top:6px"><span style="font-size: 14px;color: #6D414C;;">折后价&nbsp;&nbsp;¥</span><span
            style="font-size: 20px;color: #6D414C;"> {{ record.totalTransactionPrice }}</span></div>

        </div>
      </a-flex>

      <div style="border-bottom:1px solid #D8D8D8;width: 100%;margin: 12px 0;"/>

      <div style="text-align: right;">
        <div><span style="font-size: 14px;color: #6D414C;">应付&nbsp;&nbsp;¥</span>
          <span style="font-weight: 500;font-size: 20px;color: #6D414C;"> {{
              record.totalTransactionPrice
            }}</span></div>
      </div>

    </div>


    <div style="font-weight: 500;font-size: 16px;color: #333333;padding: 8px 0;margin: 12px 0;">
      退款信息
    </div>


    <BasicForm @register="registerForm1">
      <template #returnGoodsQty="{ model, field }">
        <a-row :gutter="24" align="middle">
          <a-col :span="8">
<!--            :max="record.totalTransactionPrice || 0"-->
            <a-input-number v-model:value="model[field]" :min="1"
              :max="record.goodsQty - record.returnGoodsQty"
              :precision="0"
              @update:value="updateQty"
              />
          </a-col>
          <a-col :span="16">
            （可退货数量：{{ record.goodsQty - record.returnGoodsQty }}）
          </a-col>
        </a-row>
      </template>

      <template #totalReturnPrice="{ model, field }">
        <a-row :gutter="24" align="middle">
          <a-col :span="24">
            <a-input-number v-model:value="model[field]" :min="0"
              :max="9999999"
              :precision="2"/>
          </a-col>
        </a-row>
      </template>

      <template #payExtensionCode="{ model, field }">
        <div class="data-group">
          <div
            :class="['use', 'cell', model[field]===o.value ? 'active' : 'tacit']"
            v-for="o in cashPayCodes"
            :key="o.value"
            @click="model[field] = o.value"
          >{{ o.label }}
          </div>
        </div>
      </template>
    </BasicForm>
    <BackDetail @register="registerDetail1" />
  </BasicDrawer>

</template>

<script setup>
import {defineOptions, reactive, ref} from 'vue';

import {BasicDrawer, useDrawerInner, useDrawer} from '@/components/Drawer';

import {useMessage} from '@/hooks/web/useMessage';
import {useForm} from "@/components/Form";
import {backList, cashPayCodes} from "@/api/ds.js";
import {BasicForm} from "@/components/Form";
import {POST} from "@/api/http.js";
import {getUserInfo} from "@/utils/auth";
import {round} from "@/api/util.js";
import {getProductDiscount} from "@/views/member/util.js";

import BackDetail from "../member/back-detail.vue";

defineOptions({name: 'OrderRefund'});

const emit = defineEmits(['complete']);
const state = reactive({title: ''});
const record = ref({});
const orderHeader = ref([]);


const {createMessage} = useMessage();

const [registerForm1, form1] = useForm({
  labelWidth: 100,
  baseColProps: {span: 24, style: {paddingRight: '36px'}},

  schemas: [
    {
      label: '退货数量',
      field: 'returnGoodsQty',
      required: true,
      component: 'InputNumber',
      slot: 'returnGoodsQty',
    },

    {
      label: '物品情况',
      field: 'isBack',
      required: true,
      show: false,
      component: 'RadioGroup',
      componentProps: {
        options: backList,
      },
    },

    {
      label: '退款金额',
      field: 'totalReturnPrice',
      required: true,
      component: 'InputNumber',
      componentProps: {
        min: 0,
        precision: 2,
      },
      slot: 'totalReturnPrice',
    },

    {
      label: '退款方式',
      field: 'payExtensionCode',
      required: true,
      component: 'RadioGroup',
      slot: 'payExtensionCode',
    },


    {
      label: '退款原因',
      field: 'cancelCustom',
      required: true,
      component: 'InputTextArea',
      componentProps: {
        rows: 6,
        maxlength: 200,
        showCount: true,
      },
    },


  ],
  showActionButtonGroup: false,
});
const [registerDetail1, { openDrawer: TDlDrawer }] = useDrawer();


const [registerDrawer, {closeDrawer}] = useDrawerInner(async ({orderHeader: header, record: item}) => {
  orderHeader.value = header;
  record.value = item;

  await form1.resetFields();

      form1.setFieldsValue({
        totalReturnPrice: item.totalTransactionPrice / item.goodsQty * (item.goodsQty - item.returnGoodsQty),
        returnGoodsQty: item.goodsQty - item.returnGoodsQty,
      });
  form1.updateSchema([{field: 'isBack', show: item.itemGoodsType === 1}]);
});

function updateQty(value) {
  let count = record.value?.goodsQty - record.value?.returnGoodsQty;
  count = count <= 0 ? 1 : count;
  form1.setFieldsValue({
    totalReturnPrice: round(record.value?.totalTransactionPrice / (record.value?.goodsQty??1) * value),
  });
}

async function onSave() {
  const formData = form1.getFieldsValue();
  const {cancelCustom, payExtensionCode, returnGoodsQty, totalReturnPrice, isBack} = formData;

  const {
    itemGoodsType, extensionCode, goodsQty,
    goodsSn, goodsName, extensionId, storeCode, benefitsType
  } = record.value;

  const refundChannels = 2;

  const {
    employeeCode: cashierCode,
    realName: cashierName,
  } = (await getUserInfo())?.resultBean ?? {};

  const {masterOrderSn, memberCode} = orderHeader.value;
  const returnPrice = round(totalReturnPrice );

  const item = {
    payExtensionCode,
    itemGoodsType,
    extensionCode,
    goodsQty: returnGoodsQty,
    returnGoodsQty,
    returnPrice,
    totalReturnPrice: round(totalReturnPrice),
    isBack,
    goodsSn,
    goodsName,
    extensionId,
    storeCode,
    benefitsType,
    refundChannels,
    cashierCode,
    cashierName
  };

  const data = {
    masterOrderSn,memberCode,
    cashierCode, cashierName, cancelCustom,
    source: '21', referer: 'PC端',
    orderItemBeanList: [item]
  };

  const res = await POST('/cashier/createTDShopOrders', data);
  createMessage.success('退款成功');
  TDlDrawer(true, { record: res });
  emit('complete')
  // closeDrawer();
}
</script>

<style lang="less" scoped>
.card {
  margin: 8px 0 46px;
  padding: 12px;

  .c-title {
    display: flex;
    flex-direction: row;
    align-items: center;
    column-gap: 8px;
    color: #091f3d;
    font-size: 15px;
    font-weight: 600;
  }

  .c-body {
    margin-top: 16px;

    .label {
      color: #acb4bf;
    }

    .value {
      color: #091f3d;
    }
  }
}
</style>


<style lang="less" scoped>

.data-group {
  display: flex;
  flex-flow: row wrap;
  align-items: center;
  cursor: pointer;
  gap: 8px 12px;

  .cell {
    padding: 4px 20px;
    border-radius: 4px;
    font-size: 14px;
    font-weight: 400;
  }

  .tacit {
    border: 1px solid #e0e5ec;
    color: #091f3d;
  }

  .active {
    border: 1px solid @primary-color;
    background-color: @primary-color;
    color: #fff;
  }
}
</style>
